home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Gold Collection / Software Vault - The Gold Collection (American Databankers) (1993).ISO / cdr26 / netprog.zip / NETPROG.TAR / ipc / tim_shmcli.c < prev    next >
C/C++ Source or Header  |  1989-12-17  |  2KB  |  80 lines

  1. #include    <stdio.h>
  2. #include    <sys/types.h>
  3. #include    <sys/ipc.h>
  4. #include    <sys/shm.h>
  5.  
  6. #include    "shm.h"
  7.  
  8. #define    NUMMESG    10000
  9. #define    MESGLEN    2048
  10.  
  11. int    shmid, clisem, servsem;    /* shared memory and semaphore IDs */
  12. Mesg    *mesgptr;        /* ptr to message structure, which is
  13.                    in the shared memory segment */
  14.  
  15. main()
  16. {
  17.     /*
  18.      * Get the shared memory segment and attach it.
  19.      * The server must have already created it.
  20.      */
  21.  
  22.     if ( (shmid = shmget(SHMKEY, sizeof(Mesg), 0)) < 0)
  23.         err_sys("client: can't get shared memory segment");
  24.     if ( (mesgptr = (Mesg *) shmat(shmid, (char *) 0, 0)) == (Mesg *) -1)
  25.         err_sys("client: can't attach shared memory segment");
  26.  
  27.     /*
  28.      * Open the two semaphores.  The server must have
  29.      * created them already.
  30.      */
  31.  
  32.     if ( (clisem = sem_open(SEMKEY1)) < 0)
  33.         err_sys("client: can't open client semaphore");
  34.     if ( (servsem = sem_open(SEMKEY2)) < 0)
  35.         err_sys("client: can't open server semaphore");
  36.  
  37.     client();
  38.  
  39.     /*
  40.      * Detach and remove the shared memory segment and
  41.      * close the semaphores.
  42.      */
  43.  
  44.     if (shmdt(mesgptr) < 0)
  45.         err_sys("client: can't detach shared memory");
  46.     if (shmctl(shmid, IPC_RMID, (struct shmid_ds *) 0) < 0)
  47.         err_sys("client: can't remove shared memory");
  48.  
  49.     sem_close(clisem);    /* will remove the semaphore */
  50.     sem_close(servsem);    /* will remove the semaphore */
  51.  
  52.     exit(0);
  53. }
  54.  
  55. client()
  56. {
  57.     int    i;
  58.  
  59.     /*
  60.      * Tell the server we're here and ready,
  61.      * then just receive while the server sends us things.
  62.      */
  63.  
  64.     sem_wait(clisem);        /* get control of shared memory */
  65.     mesgptr->mesg_len = MESGLEN;
  66.     mesgptr->mesg_type = MESGLEN;
  67.     sem_signal(servsem);        /* wake up server */
  68.  
  69.     for (i = 0; i < NUMMESG; i++) {
  70.         sem_wait(clisem);    /* wait for server */
  71.  
  72.         if (mesgptr->mesg_len != MESGLEN)
  73.             err_sys("client: incorrect length");
  74.         if (mesgptr->mesg_type != (i + 1))
  75.             err_sys("client: incorrect type");
  76.  
  77.         sem_signal(servsem);    /* wake up server */
  78.     }
  79. }
  80.